<template>
  <div class="container">
    <div class="top" ref="topRef">
      <el-form :inline="true" :model="params" class="grids gridColumns6">
        <el-form-item :label="item.label" v-for="(item,index) in searchs" :key="index">
          <courseTypCascader v-model="params[item.value]" v-if="item.value=='type'"></courseTypCascader>
          <courseQuery multiple="1" v-model="params[item.value]" v-else-if="item.value=='curriculum_id'"></courseQuery>
          <el-select v-model="params[item.value]" :placeholder="`请选择${item.label}`" v-else-if="item.value=='workYears'">
            <el-option v-for="(item,index) in workYears.split(',')" :key="index" :label="item" :value="item" />
          </el-select>
          <dictSelect @fatherMethods="search" v-model="params.affiliation" dictCode="registration_affiliation" multiple="1" v-else-if="item.value=='affiliation'"></dictSelect>
          <DatePicker v-model="params.year" type="year" v-else-if="item.value=='year'"></DatePicker>
          <el-select v-else-if="item.value=='status'" collapse-tags collapse-tags-tooltip :max-collapse-tags="2" multiple clearable v-model="params.status" placeholder="请选择订单状态" @change='search'>
            <el-option v-for="(item,index) in tabs" :key="index" :label="item.name" :value="item.value" />
          </el-select>
          <el-input v-model="params[item.value]" :placeholder="`请输入${item.label}`" v-else @change="search" />
        </el-form-item>

        <el-form-item>
          <el-dropdown>
            <el-button type="primary">操作</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="search">查询</el-dropdown-item>
                <el-dropdown-item :disabled="!selectData.length" @click="proxy.$refs.editMoxueyuanRef.open(selectData)">设置课程标签</el-dropdown-item>
                <el-dropdown-item @click="counter.exportAttachment(selectData)" :disabled="!selectData.length">批量下载附件</el-dropdown-item>
                <el-dropdown-item @click="delBatch" :disabled="!selectData.length">批量删除</el-dropdown-item>
                <el-dropdown-item @click="proxy.$refs.orderInfoExportRef.open(selectData)" :disabled="!selectData.length">订单信息导出</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <el-button @click="dataInit" style="margin-left: 10px;">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="actionBtn flex alignCenter" v-if="false">
        <el-button type="primary" @click="proxy.$refs.inputFile.click()" plain v-if="counter.isAdmin">更新模板</el-button>
        <el-button type="primary" @click="downLoadTemplate" plain>下载模板</el-button>
        <el-button type="primary" @click="toImport(1)" plain :loading="importLoading">导入模板</el-button>
        <el-button type="primary" :disabled="!selectData.length" plain @click="proxy.$refs.editMoxueyuanRef.open(selectData)">设置课程标签</el-button>
        <!--  <el-button type="primary" @click="toImport(2)" plain :loading="importLoading">导入身份证附件</el-button>
      <el-button type="primary" @click="toImport(3)" plain :loading="importLoading">导入毕业证附件</el-button>
      <el-button type="primary" @click="toImport(4)" plain :loading="importLoading">导入工作证明附件</el-button> -->
        <!-- <el-button type="primary" @click="proxy.$refs.fileHistoryImportRef.click()" plain :loading="importLoading">历史订单导入</el-button> -->
        <el-button type="primary" @click="counter.exportAttachment(selectData)" :disabled="!selectData.length">批量下载附件</el-button>
        <el-button type="danger" plain @click="delBatch" :disabled="!selectData.length">批量删除</el-button>
        <!-- <el-button type="primary" @click="proxy.$refs.orderExportExcelRef.open(params,selectData)" plain>导出</el-button> -->
        <el-button type="primary" @click="proxy.$refs.orderInfoExportRef.open(selectData)" plain :disabled="!selectData.length">订单信息导出</el-button>
        <!-- <el-button type="danger" @click="clearAll">清空全部数据</el-button> -->
      </div>
    </div>

    <el-table ref="tableRef" :data="tableData.rows" v-loading="loading" stripe :max-height="tableMaxHeight" @select-all="selectAll" @select="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="报名时间" width="220" fixed="left">
        <template #default="scope">
          <div class="flex alignCenter">
            {{proxy.$utils.dateTimeFormateFn(scope.row._add_time,"all")}}
            <div v-if="scope.row.statisticsYear" class="statisticsYear fz12">延</div>
            <div class="minus classStatus" v-if="scope.row.status==10">减</div>
            <el-tooltip class="box-item" effect="dark" :content="scope.row.class_info_show.className" placement="top" v-if="scope.row.class_info_show">
              <div @click="proxy.$utils.toLink(`/classManage/classDetails?classId=${scope.row.class_info_show._id}`)" class="classStatus fz12 bold" :class="{active:scope.row.class_info_show.status!=2}">{{scope.row.class_info_show.status==2?'结':"读"}}</div>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="approvalContent.model.name" label="姓名" width="70" fixed="left">
        <template #default="scope">
          <div class="button" @click="proxy.$refs.registrationDetailsRef.open(scope.row)">{{scope.row.approvalContent.model.name}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="approvalContent.model.mobile" label="联系方式" width="110" fixed="left" />
      <!-- <el-table-column label="培训分类" width="270">
        <template #default="scope">
          {{type_format(scope.row.curriculum_Info.type)}}
        </template>
      </el-table-column> -->
      <el-table-column prop="curriculum_Info.name" label="课程名称" width="360" show-overflow-tooltip />
      <el-table-column prop="approvalContent.model.identityCard" label="身份证号" width="179" />
      <el-table-column prop="approvalContent.model.graduationMajor" label="所在企业名称" width="200" show-overflow-tooltip>
        <template #default="scope">
          {{counter.showEnterprise(scope.row.approvalContent.model,"enterprise")}}
        </template>
      </el-table-column>
      <el-table-column prop="approvalContent.model.employed_Status" label="就业状态" align="center" width="80" show-overflow-tooltip>
        <template #default="scope">
          {{scope.row.approvalContent.model.employed_Status||'-'}}
        </template>
      </el-table-column>
      <el-table-column prop="approvalContent.model.workYears" label="累计工作年限" width="110">
        <template #default="scope">
          {{scope.row.approvalContent.model.workYears||'-'}}
        </template>
      </el-table-column>
      <el-table-column label="最高学历" width="165" prop="approvalContent.model.education" />
      <el-table-column prop="approvalContent.model.graduationMajor" label="毕业专业" width="180" show-overflow-tooltip>
        <template #default="scope">
          {{scope.row.approvalContent.model.graduationMajor||'-'}}
        </template>
      </el-table-column>
      <el-table-column prop="out_trade_no" label="订单号" width="170" />
      <el-table-column label="报名所属" width="150" show-overflow-tooltip>
        <template #default="scope">
          <dictSelect v-if="scope.row.class_Info&&scope.row.class_Info.affiliation" v-model="scope.row.class_Info.affiliation" dictCode="registration_affiliation" readonly="1"></dictSelect>
        </template>
      </el-table-column>

      <el-table-column prop="updateUser" label="操作人" width="100">
        <template #default="scope">
          {{(scope.row.refund_info&&scope.row.refund_info.updateUser)||scope.row.updateUser}}
        </template>
      </el-table-column>
      <el-table-column prop="displayPrice" label="订单金额" align="right" fixed="right" width="90">
        <template #default="scope">
          <div class="flex alignCenter justifyEnd">
            {{proxy.$utils.formatNumber(scope.row.displayPrice)}}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="报名状态" width="120" align="center" fixed="right">
        <template #default="scope">
          <el-tag type="danger" v-if="scope.row.status == 1 && scope.row.rejectMsg">已驳回</el-tag>
          <el-tag v-else :color="tagBgColor(scope.row.status)">
            <div :style="{color:tagColor(scope.row.status)}">{{status_format(scope.row.status)}}</div>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" align="center" fixed="right">
        <template #default="scope">
          <div class="flex alignCenter">
            <div class="actionText" v-if="canEdit(scope.row.status)" @click="handleClick(scope.row,1)">编辑</div>
            <el-divider direction="vertical" class="line" v-if="scope.row.status != 4" />
            <el-dropdown v-if="scope.row.status != 4">
              <div class="flex alignCenter">
                <div class="actionText">更多</div>
                <el-icon><arrow-down /></el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :disabled="!showInvoiceCancel(scope.row)" @click="proxy.$refs.invoiceCancelRef.open(scope.row.out_trade_no)">红冲发票</el-dropdown-item>
                  <el-dropdown-item @click="handleClick(scope.row,2)" :disabled="scope.row.status != 1">审批</el-dropdown-item>
                  <el-dropdown-item :disabled="!canshowRefund(scope.row)" @click="proxy.$refs.refundPopRef.open(scope.row)">退款</el-dropdown-item>
                  <el-dropdown-item :disabled="![2,10].includes(scope.row.status)" @click="proxy.$refs.discountsReductionsRef.open(scope.row._id)">优惠减免</el-dropdown-item>
                  <el-dropdown-item :disabled="!isShowInvoicing(scope.row)" @click="handleClick(scope.row,3)">开票</el-dropdown-item>
                  <el-dropdown-item :disabled="!counter.isAdmin" @click="handleClick(scope.row,4)">修改订单</el-dropdown-item>
                  <el-dropdown-item :disabled="scope.row.hasOwnProperty('statisticsYear')" @click="handleClick(scope.row,5)">延至次年</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <Pagination :selectNum="selectData.length" v-if="tableData['total']" :total="tableData['total']" v-model:page="params.pageIndex" v-model:limit="params.pageSize" @pagination="getInfo" :totalPrice="total" />

    <registrationDetails ref="registrationDetailsRef"></registrationDetails>

    <!-- 退款 -->
    <refundPop ref="refundPopRef" @fatherMethod="getInfo"></refundPop>

    <input type="file" @change="handleFileUpload" v-show="false" ref="inputFile" />

    <!-- 订单导入 -->
    <input type="file" @change="handleFileImport" v-show="false" ref="fileClick" />

    <!-- 历史订单 -->
    <input type="file" @change="handleFileHistoryImport" v-show="false" ref="fileHistoryImportRef" />

    <!-- 审批 -->
    <el-dialog v-model="dialogVisible" title="审批" width="500" :before-close="handleClose">
      <el-form :model="model" class="demo-form-inline">
        <el-form-item label="是否通过">
          <el-radio-group v-model="model.result">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="0">驳回</el-radio>
            <el-radio :label="3">审核未通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="model.content" :autosize="{ minRows:  4 }" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="save" :loading="loading">
            确 认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <editOrderInfo ref="editOrderInfoRef" @fatherMethod="getInfo"></editOrderInfo>

    <!-- 导入失败 -->
    <importOrderError ref="importOrderErrorRef"></importOrderError>

    <!-- 导出 -->
    <orderExportExcel ref="orderExportExcelRef"></orderExportExcel>

    <!-- 开票 -->
    <invoiceApply ref="invoiceApplyRef" @fatherMethod="getInfo"></invoiceApply>

    <!-- 红冲发票 -->
    <invoiceCancel ref="invoiceCancelRef" @fatherMethod="getInfo"></invoiceCancel>

    <!-- 设置魔学院 -->
    <editMoxueyuan ref="editMoxueyuanRef" @fatherMethod="getInfo"></editMoxueyuan>

    <!-- 优惠减免 -->
    <discountsReductions ref="discountsReductionsRef" @fatherMethod="getInfo"></discountsReductions>

    <!-- 订单信息导出 -->
    <orderInfoExport ref="orderInfoExportRef"></orderInfoExport>
  </div>
</template>

<script setup lang="ts">
//订单信息导出
import orderInfoExport from "@/views/order/components/orderInfoExport.vue";
//优惠减免
import discountsReductions from "@/views/order/components/discountsReductions.vue";
//设置魔学院
import editMoxueyuan from "@/views/order/components/editMoxueyuan.vue";
// 红冲发票
import invoiceCancel from "@/views/order/components/invoiceCancel.vue";
import invoiceApply from "@/views/order/components/invoiceApply.vue";
import orderExportExcel from "@/views/order/components/orderExportExcel.vue";
//导入失败
import importOrderError from "@/views/order/components/importOrderError.vue";
import editOrderInfo from "@/views/order/components/editOrderInfo.vue";
import refundPop from "@/views/order/components/refundPop.vue";
//订单详情
import registrationDetails from "@/views/order/components/registrationDetails.vue";
import useCounterStore from "@/store/counter";
const counter = useCounterStore();
const instance = getCurrentInstance();
const { proxy } = getCurrentInstance();

let tabs = ref([
  { name: "待审核", value: 1 },
  { name: "审核未通过", value: 3 },
  { name: "支付尾款", value: 8 },
  { name: "报名成功", value: 2 },
  { name: "优惠减免", value: 10 },
  // { name: "已退款", value: 4 },
  // { name: "部分退款", value: 9 },
  { name: "已开票", value: 7 },
]);

let searchShowNum = ref(4);
let workYears = ref(
  "应届毕业年,不满1年,满1年,满2年,满3年,满4年,满5年,满6年,满7年,满8年,满9年,满10年及以上"
);
let model = ref({
  content: "",
  result: 1, //1:通过 2:拒绝
});
let importLoading = ref(false);
let loading = ref(false);

let dialogVisible = ref(false);
let selectData = ref([]); //选中的数据

let params = ref({
  pageIndex: 1,
  pageSize: 50,
  isAdmin: 1,
  curriculum_id: "",
  name: "",
  mobile: "",
  workYears: "",
  identityCard: "",
  graduationMajor: "",
  out_trade_no: "",
  affiliation: "",
  year: proxy.$utils.dateTimeFormateFn(Date.now(), "year"),
  status: "",
});
let searchs = ref([
  { label: "年份", value: "year" },
  { label: "课程名称", value: "curriculum_id" },
  { label: "姓名", value: "name" },
  { label: "联系方式", value: "mobile" },
  { label: "身份证号", value: "identityCard" },
  { label: "毕业专业", value: "graduationMajor" },
  { label: "订单状态", value: "status" },
  { label: "订单号", value: "out_trade_no" },
  { label: "所在企业名称", value: "enterprise" },
  // { label: "培训分类", value: "type" },
  { label: "累计工作年限", value: "workYears" },
  { label: "报名所属", value: "affiliation" },
]);
let tableData = ref([]);
let types = [];
let isShow = ref(true);
let orderInfo = {}; //订单信息
let importType = null; //导入类型
let classList = []; //班级列表
let topHeight = ref(0);

onMounted(async () => {
  await class_info();
  getTypes();
  getInfo();
  nextTick(() => {
    topHeight.value = proxy.$refs.topRef.offsetHeight;
  });
});

let tableMaxHeight = computed(() => {
  let hei = window.innerHeight - 84 - counter.pageHeight - 55 - topHeight.value;
  return `${hei}px`;
});

let total = computed(() => {
  let num = 0;
  tableData.value.rows.forEach((element) => {
    num += element.displayPrice;
  });
  return num;
});

function toImport(num) {
  importType = num;
  proxy.$refs.fileClick.click();
}

function showInvoiceCancel(e) {
  if (e.dataForm && e.dataForm == "file") return false;
  if (e.status == 7) return true;
}

//班级信息
async function class_info() {
  classList = await proxy.$apis.classData({ type: "query" });
  console.log("全部班级", classList);
}

function refund_amount_format(row) {
  let str;
  if (row.hasOwnProperty("balance_refund_info")) {
    str = row.refund_info && row.refund_info.refund_amount.total / 100;
    str +=
      row.balance_refund_info &&
      row.balance_refund_info.refund_amount.total / 100;
  } else if (row.refund_info && row.refund_info.refund_amount) {
    str = row.refund_info && row.refund_info.refund_amount.total / 100;
  } else {
    str = 0;
  }
  if (str) return proxy.$utils.formatNumber(str.toString());
  return "-";
}

let isShowInvoicing = (e) => {
  if (e.dataForm && e.dataForm == "file") return false;
  return (
    [2, 10].includes(e.status) && proxy.$utils.isEmptyObject(e.invoicing_Info)
  );
};

function handleSelectionChange(e, k) {
  //selectData.value = e;
  if (proxy.$utils.isFieldEqual(e, "_id", k._id)) {
    selectData.value.push(k);
  } else {
    let index = proxy.$utils.findIndexByField(selectData.value, "_id", k._id);
    if (index != -1) selectData.value.splice(index, 1);
  }
  //console.log("selectData.value", selectData.value);
}

function selectAll(array) {
  if (array.length) {
    array.forEach((element) => {
      if (proxy.$utils.isFieldEqual(selectData.value, "_id", element._id)) {
      } else {
        selectData.value.push(element);
      }
    });
  } else {
    console.log("array is empty", tableData.value);
    if (tableData.value.rows && tableData.value.rows.length) {
      tableData.value.rows.forEach((element) => {
        let index = proxy.$utils.findIndexByField(
          selectData.value,
          "_id",
          element._id
        );
        if (index != -1) selectData.value.splice(index, 1);
      });
    }
  }
  //console.log("selectData.value", selectData.value);
}

function tagBgColor(e) {
  switch (e) {
    case 0:
      return "#FAD5C1";
      break;
    case 1:
      return "#FCF9D7";
      break;
    case 2:
      return "#ECF7E8";
      break;
    case 3:
      return "#F7E7F7";
      break;
    case 4:
      return "#E5BCBE";
      break;
    case 7:
      return "#E0F3FB";
      break;
    case 10:
      return "#ECF7E8";
      break;
    default:
      break;
  }
}

function tagColor(e) {
  switch (e) {
    case 0:
      return "#D07743";
      break;
    case 1:
      return "#F5C73C";
      break;
    case 2:
      return "#35965F";
      break;
    case 3:
      return "#663786";
      break;
    case 4:
      return "#A51C1B";
      break;
    case 7:
      return "#216592";
      break;
    case 10:
      return "#35965F";
      break;
    default:
      break;
  }
}

//能否退款
function canshowRefund(e) {
  if (e.dataForm && e.dataForm == "file") return false;
  return [1, 2, 3, 8, 9, 10].includes(e.status);
}

//订单能否编辑
function canEdit(e) {
  let arr = [4];
  return !arr.includes(e);
}

async function delBatch() {
  let resp = await proxy.$utils.confirmTips("确认删除选中订单?");
  if (!resp) return;
  let list = proxy.$utils.deepcopy(selectData.value);
  for (let index = 0; index < list.length; index++) {
    const element = list[index];
    await proxy.$apis.orderAction({
      type: "del",
      data: { _id: element._id },
    });
  }
  proxy.$utils.showToast("删除成功");
  getInfo("init");
}

async function clearAll() {
  let resp = await proxy.$utils.confirmTips("确认清空全部数据?");
  if (!resp) return;
  await proxy.$apis.orderAction({
    type: "clearAll",
  });
  getInfo();
  proxy.$utils.showToast("清空成功");
}

function search() {
  params.value.pageIndex = 1;
  getInfo();
}

function dataInit() {
  params.value = {
    pageIndex: 1,
    pageSize: 50,
    status: "",
    isAdmin: 1,
    curriculum_id: "",
    name: "",
    mobile: "",
    workYears: "",
    identityCard: "",
    graduationMajor: "",
    out_trade_no: "",
    year: proxy.$utils.dateTimeFormateFn(Date.now(), "year"),
    affiliation: "",
  };
  selectData.value = [];
  getInfo();
}

async function downLoadTemplate() {
  counter.downLoadTemplate("order", "订单导入模板");
}

async function handleFileHistoryImport(event) {
  const files = event.target.files;
  let file = files[0];
  let resp = await proxy.$utils.fileToJson(file);
  let list = [];
  for (let index = 0; index < resp.length; index++) {
    const element = resp[index];
    if (index) {
      list.push({
        out_trade_no: element[0],
        updateUser: element[1],
      });
    }
  }
  await proxy.$apis.fileTemplate({
    data: { type: "oldOrderImport", list },
    type: "import",
  });
  getInfo();
}

async function handleFileImport(event) {
  try {
    importLoading.value = true;
    const files = event.target.files;
    let file = files[0];
    switch (importType) {
      case 1: //订单导入
        await importOrder(file);
        break;
      case 2: //身份证导入
        await importIdCard(file);
        break;
      case 3: //毕业证导入
        await importGraduation(file);
        break;
      case 4: //工作证明导入
        await importProofWork(file);
        break;
      default:
        break;
    }
  } catch (error) {
    console.log("导入啥毛病", error);
  } finally {
    event.target.value = "";
    importLoading.value = false;
  }
}

//工作证明
async function importProofWork(file) {
  let resp = await proxy.$utils.fileToJson(file);
  //return console.log("工作证明", resp);
  let list = [];
  for (let index = 0; index < resp.length; index++) {
    const element = resp[index];
    if (index && element[0])
      list.push({ out_trade_no: element[0], url: element[1] });
  }
  await proxy.$apis.fileTemplate({
    data: { type: "orderProofWork", list },
    type: "import",
  });
}

async function importGraduation(file) {
  let resp = await proxy.$utils.fileToJson(file);
  //return console.log("毕业证明", resp);
  let list = [];
  for (let index = 0; index < resp.length; index++) {
    const element = resp[index];
    if (index) list.push({ out_trade_no: element[0], url: element[1] });
  }
  await proxy.$apis.fileTemplate({
    data: { type: "orderGraduation", list },
    type: "import",
  });
}

async function importIdCard(file) {
  let resp = await proxy.$utils.fileToJson(file);
  let list = [];
  for (let index = 0; index < resp.length; index++) {
    const element = resp[index];
    if (index) list.push({ out_trade_no: element[0], url: element[1] });
  }
  await proxy.$apis.fileTemplate({
    data: { type: "orderIdCard", list },
    type: "import",
  });
}

async function importOrder(file) {
  let resp = await proxy.$utils.fileToJson(file);
  let list = [];
  resp.forEach((element, index) => {
    if (index && element[0]) {
      list.push({
        _add_time_str: proxy.$utils.dateTimeFormateFn(element[0], "all"),
        curriculum_name: element[1],
        affiliation: ["/", "-"].includes(element[2]) ? "" : element[2],
        name: element[3],
        mobile: element[4],
        identityCard: element[5],
        graduationMajor: element[6],
        workYears: element[7],
        selectLesson: element[8],
        price: element[9],
        email: ["/", "-"].includes(element[10]) ? "" : element[10],
        education: element[11],
        enterprise: ["/", "-"].includes(element[12]) ? "" : element[12],
        enterpriseTax: ["/", "-"].includes(element[13]) ? "" : element[13],
        enterpriseJurisdiction: ["/", "-"].includes(element[14])
          ? ""
          : element[14],
        updateUser: counter.updateUser,
        dataForm: "file",
      });
    }
  });
  let { errorList, successList } = await proxy.$apis.fileTemplate({
    data: { type: "order", list },
    type: "import",
  });

  if (successList.length && !errorList.length) {
    getInfo();
    proxy.$utils.showToast("导入成功");
  } else if (errorList.length) {
    proxy.$refs.importOrderErrorRef.open(errorList);
  }
}

async function handleFileUpload(event) {
  let file = {
    name: "",
    path: "",
    type: "order",
  };
  const files = event.target.files;
  file.name = files[0].name;
  file.path = await counter.uploadFile(files[0]);
  await proxy.$apis.fileTemplate({
    data: file,
    type: "update",
  });
  proxy.$utils.showToast("上传成功");
}

function status_format(e) {
  if (e == 8) {
    return "支付尾款";
  } else if (e == 10) {
    return "报名成功";
  } else {
    for (let index = 0; index < tabs.value.length; index++) {
      const element = tabs.value[index];

      if (element.value == e) return element.name;
    }
  }
}

function type_format(e) {
  if (!types.length) return;
  if (!e) return;
  let index = proxy.$utils.findIndexByField(types, "_id", e[0]);
  return types[index].name;
}

async function getTypes() {
  types = await proxy.$apis.webCurriculum({
    type: "query",
  });
}

function tabClick(tab: TabsPaneContext, event: Event) {
  init(tab.index);
}

async function save() {
  try {
    loading.value = true;
    if (model.value.result == 0) {
      if (!model.value.content.trim()) {
        return proxy.$utils.showToast("请输入驳回原因", 0);
      }
      await proxy.$apis.orderAction({
        type: "update",
        data: {
          rejectMsg: model.value.content,
          orderId: model.value._id,
          updateUser: counter.updateUser,
        },
      });
    } else if (model.value.result == 1) {
      //审核通过
      let obj = {
        status: 2,
        orderId: model.value._id,
        updateUser: counter.updateUser,
      };
      //如果是预报名
      if (orderInfo["signUpPrice"]) {
        //如果是手动修改的订单
        if (orderInfo["manualPrice"] && orderInfo["manualPrice"] == 1) {
          if (orderInfo["price"] > 0) obj["status"] = 8;
        } else {
          let signUpPrice = orderInfo["signUpPrice"];
          let price = orderInfo["price"];
          if (price - signUpPrice > 0) obj["status"] = 8;
        }
      }
      await proxy.$apis.orderAction({
        type: "update",
        data: obj,
      });
    } else {
      //审核未通过
      await proxy.$apis.orderAction({
        type: "update",
        data: {
          status: 3,
          orderId: model.value._id,
          updateUser: counter.updateUser,
        },
      });
    }
    proxy.$utils.showToast("操作成功");
    handleClose();
  } catch (error) {
    console.log("审批的时候报错", error);
  } finally {
    loading.value = false;
  }
}

function handleClose() {
  model.value = {
    content: "",
    result: 1, //1:通过 2:拒绝
  };
  getInfo();
  dialogVisible.value = false;
}

async function handleClick(row, num) {
  switch (num) {
    case 1:
      let result = await proxy.$apis.course({
        type: "details",
        data: { _id: row.curriculum_id },
      });
      instance.refs.editOrderInfoRef.open(result, row.approvalContent, {
        orderId: row._id,
        userId: row.userId,
      });
      break;
    case 2:
      //订单信息赋
      orderInfo = proxy.$utils.deepcopy(row);
      model.value._id = row._id;
      dialogVisible.value = true;
      break;
    case 3:
      proxy.$refs.invoiceApplyRef.open(row);
      break;
    case 4: //修改订单价格
      proxy.$refs.registrationDetailsRef.open(row, 1);
      break;
    case 5: //延至次年
      let res = await proxy.$utils.confirmTips(
        `是否将${row.approvalContent.model.name}的订单延至次年?`
      );
      if (!res) return;
      let year = proxy.$utils.dateTimeFormateFn(row._add_time, "year");
      let statisticsYear = year * 1 + 1;
      await proxy.$apis.orderAction({
        type: "update",
        data: {
          statisticsYear,
          orderId: row._id,
          updateUser: counter.updateUser,
        },
      });
      proxy.$utils.showToast("操作成功");
      getInfo();
      break;
    default:
      break;
  }
}

function init(index) {
  params.value.status = tabs.value[index].value;
  params.value.pageIndex = 1;
  getInfo();
}

function classIdStatus(e) {
  let index = proxy.$utils.findIndexByField(classList, "_id", e.classId);
  if (index != -1) return classList[index];
}

async function getInfo(type?) {
  try {
    loading.value = true;
    let resp = await proxy.$apis.orderAction({
      type: "list",
      data: params.value,
    });
    for (let index = 0; index < resp.rows.length; index++) {
      const element = resp.rows[index];
      if (element.class_Info && element.class_Info.classId) {
        element.class_info_show = classIdStatus(element.class_Info);
      }
    }
    tableData.value = resp;
    console.log("列表", tableData.value);
    if (type && type == "init") {
      selectData.value = [];
    } else {
      nextTick(() => {
        selectData.value.forEach((element) => {
          let a = tableData.value.rows.find((el) => {
            return element._id == el._id; // 注意这里寻找的字段要唯一，示例仅参考
          });
          if (a) proxy.$refs.tableRef.toggleRowSelection(a, true);
        });
      });
    }
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

watch(
  () => [
    params.value.year,
    params.value.curriculum_id,
    params.value.affiliation,
    params.value.workYears,
    params.value.type,
  ],
  (newValue, oldValue) => {
    if (newValue) search();
  },
  { deep: true, immediate: true }
);
</script>



<style lang="scss" scoped>
.container {
  margin: 20px;
  .el-tag {
    border-color: transparent;
  }
  .actionBtn {
    margin-bottom: 15px;
  }
  .el-icon {
    color: var(--el-color-primary);
    margin-left: 2px;
  }
  .actionText {
    cursor: pointer;
    color: var(--el-color-primary);
    font-size: 14px;
  }
  .line {
    height: 20px;
  }
  .statisticsYear {
    background: var(--el-color-primary);
    color: white;
    border-radius: 50%;
    margin-left: 5px;
    width: 18px;
    height: 18px;
    line-height: 18px;
    text-align: center;
  }
  .classStatus {
    border-radius: 50%;
    margin-left: 5px;
    width: 18px;
    height: 18px;
    line-height: 18px;
    text-align: center;
    color: #97999e;
    border: 1px solid #97999e;
    cursor: pointer;
    font-size: 12px;
    font-weight: bold;
  }
  .active {
    color: #3fcf66 !important;
    border: 1px solid #3fcf66 !important;
  }
  .minus {
    color: #f66604 !important;
    border: 1px solid #f66604 !important;
  }
}
</style>



